#!/bin/bash

set -e

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

function log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

function log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

function log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

function main() {
    log_info "开始构建 cmdb-agent..."
    
    # 创建构建目录
    mkdir -p ./build
    
    # 编译二进制文件
    log_info "编译二进制文件..."
    # CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags="-s -w" -o ./build/cmdb-agent ../main.go
    cd .. 
    make all
    
    if [ ! -f ./build/cmdb-agent ]; then
        log_error "编译失败，未生成二进制文件"
        exit 1
    fi
    
    log_info "编译成功，文件大小: $(du -h ./build/cmdb-agent | awk '{print $1}')"
    
    # 上传到 OSS
    log_info "上传二进制文件到 OSS..."
    upload123 cp ./build/cmdb-agent oss://cmdb/cmdb-agent/cmdb-agent
    
    log_info "上传配置文件到 OSS..."
    upload123 cp ../etc/config.yml oss://cmdb/cmdb-agent/config.yml
    
    log_info "上传安装脚本到 OSS..."
    upload123 cp ./install.sh oss://cmdb/cmdb-agent/install.sh
    
    log_info "上传卸载脚本到 OSS..."
    upload123 cp ./uninstall.sh oss://cmdb/cmdb-agent/uninstall.sh
    
    log_info "刷新 CDN 缓存..."
    upload123 refresh
    
    # 清理构建文件
    log_info "清理构建文件..."
    rm -rf ./build
    
    log_info "构建完成！"
    log_info "下载地址: https://123pan.bkdomain.cn/cmdb/cmdb-agent/cmdb-agent"
    log_info "配置文件: https://123pan.bkdomain.cn/cmdb/cmdb-agent/config.yml"
    log_info "安装脚本: https://123pan.bkdomain.cn/cmdb/cmdb-agent/install.sh"
    log_info "卸载脚本: https://123pan.bkdomain.cn/cmdb/cmdb-agent/uninstall.sh"
}

main 